package com.ruoyi.common.utils.express.kd100;

import java.util.*;

import org.json.JSONObject;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.ruoyi.common.utils.FBSStringUtil;


/**
 * 功能：
 *
 * @author：dell
 * @create：2020/7/7 15:50
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@Component
public class Kd100Util {

	@Value("${haoqi.express.kd100.key}")
	private String key;
	@Value("${haoqi.express.kd100.customer}")
	private String customer;

	public JSONObject getExpressJsonData(String com,String num){
		String param ="{\"com\":\"{0}\",\"num\":\"{1}\"}";
		param = FBSStringUtil.format(param,com,num);
//		String customer ="1EF6FC8CB937DC38C2FAC01A7F35271E";
//		String key = "PEFkIdXa7614";
		String sign = MD5.encode(param+key+customer);
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("param",param);
		params.put("sign",sign);
		params.put("customer",customer);
		JSONObject jsonObject = null;
		try {
			String resp = postData("http://poll.kuaidi100.com/poll/query.do", params, "utf-8").toString();
			jsonObject = new JSONObject(resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	public synchronized static String postData(String url, Map<String, String> params, String codePage) throws Exception {

		final HttpClient httpClient = new HttpClient();
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(25 * 1000);
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(30 * 1000);

		final PostMethod method = new PostMethod(url);
		if (params != null) {
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, codePage);
			method.setRequestBody(assembleRequestParams(params));
		}
		String result = "";
		try {
			httpClient.executeMethod(method);
			result = new String(method.getResponseBody(), codePage);
		} catch (final Exception e) {
			throw e;
		} finally {
			method.releaseConnection();
		}
		return result;
	}
	/**
	 * 组装http请求参数
	 *
	 * @param data
	 * @return
	 */
	private synchronized static NameValuePair[] assembleRequestParams(Map<String, String> data) {
		final List<NameValuePair> nameValueList = new ArrayList<NameValuePair>();

		Iterator<Map.Entry<String, String>> it = data.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			nameValueList.add(new NameValuePair((String) entry.getKey(), (String) entry.getValue()));
		}

		return nameValueList.toArray(new NameValuePair[nameValueList.size()]);
	}

}
